package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminUserMapper;
import com.heima.admin.service.AdminUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdUser> implements AdminUserService {
    /**
     * 后台管理员登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1.入参校验
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.校验用户名
        //根据用户名查询数据库中用户信息
        AdUser dbAdUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (dbAdUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //获取盐
        String salt = dbAdUser.getSalt();
        //3.校验密码
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes()); // 用户输入密码加盐加密
        if (!inputPwd.equals(dbAdUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //4.校验用户状态  状态,0 暂时不可用 ,1 永久不可用 , 9 正常可用
        if (dbAdUser.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.STATUS_ABNORMAL);
        }
        //5.1更新ad_user表中最后一次登录时间
        dbAdUser.setLoginTime(new Date());
        updateById(dbAdUser);
//        update(Wrappers.<AdUser>lambdaUpdate().eq(AdUser::getId,dbAdUser.getId()).set(AdUser::getLoginTime,new Date()));

        //5.2.校验OK, 下发token
        String token = AppJwtUtil.getToken(dbAdUser.getId().longValue());
        Map map = new HashMap();
        map.put("token", token);
        dbAdUser.setPassword("****");
        map.put("user", dbAdUser);

        //6.封装结果,返回

        return ResponseResult.okResult(map);
    }
}
